package com.kenyi.co.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.kenyi.co.R;
import com.kenyi.co.common.utils.RouteUtils;
import com.kenyi.co.okhttp.OkHttpUtils;
import com.kenyi.co.okhttp.callback.StringCallback;
import com.kenyi.co.ui.home.adapter.HomeMainAdapter;
import com.kenyi.co.ui.home.bean.IndexListBean;
import com.kenyi.co.ui.video.VideoDetailActivity;
import com.kenyi.co.utils.CommonUtils;
import com.kenyi.co.utils.LogU;
import com.kenyi.co.utils.NetConfig;
import com.kenyi.co.utils.SharepUtils;
import com.kenyi.co.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.kenyi.co.utils.CommonUtils.isFastClick;

/**
 * 消息内容页
 */
public class MsgContentFragment extends Fragment {


    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
    private LRecyclerView mRecyclerView = null;

    private HomeMainAdapter mDataAdapter = null;
    private String name;
    private String userFav="0";
    private Boolean is_end = false;
    private int page = 0;
    private int code = 1;
    private View mEmptyView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getArguments();
        name = bundle.getString("name");
        if (name == null) {
            name = "参数非法";
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();

        if (!userFav.equals(getFav())&&!userFav.equals("0")) {
            page = 0;
            mDataAdapter.clear();
            mLRecyclerViewAdapter.notifyDataSetChanged();
            getIndexList(name);

        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_content, container, false);
        mEmptyView = view.findViewById(R.id.empty_view);

        mRecyclerView = (LRecyclerView) view.findViewById(R.id.list);
        mDataAdapter = new HomeMainAdapter(getActivity());
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);
        DividerDecoration divider = new DividerDecoration.Builder(getActivity())
                .setHeight(R.dimen.common_30dp)
                .setPadding(R.dimen.default_divider_padding_10)
                .setColorResource(R.color.white)
                .build();
        mRecyclerView.addItemDecoration(divider);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        mRecyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                mDataAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();
                getIndexList(name);
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能
        mRecyclerView.setLoadMoreEnabled(true);
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {

                if (!is_end) {
                    page++;

                    getIndexListMore(name, page);
                } else {
                    mRecyclerView.setNoMore(true);
                }
            }
        });
        //设置底部加载文字提示
        LinearLayout adView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.home_main_header, null);
        mLRecyclerViewAdapter.addHeaderView(adView);
        mRecyclerView.setFooterViewHint("努力加载中", "已经加载全部", "网络不给力啊，点击再试一次吧");
        mRecyclerView.refresh();
        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                final IndexListBean.DatasBean item = mDataAdapter.getDataList().get(position);
                if ("0".equals(item.getType())) {
                    if (!isFastClick()) {
                        return;
                    }
                    Intent metags = new Intent(getActivity(), VideoDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id", item.getId() + "");
//                bundle.putString("id", "1907030516");
                    metags.putExtras(bundle);
                    startActivity(metags);
                } else {

                    if (5 == item.getItemType()) {

                    } else {

                        Map<String, String> params = new HashMap<>();


                        params.put("title", "");
                        params.put("articleId", "");
                        params.put("url2", item.getAds().get(0).getUrl2());
                        params.put("advid", item.getAds().get(0).getId());
                        params.put("adPosition", "0");
                        params.put("pageName", CommonUtils.getTopActivity(getActivity()));
                        params.put("carrierName", CommonUtils.getOperator(getActivity()));
                        RouteUtils.RoutebyAd(getActivity().getApplicationContext(), getActivity(), item.getAds().get(0).getUrl(), params);
                    }

                }

            }
        });
        return view;
    }


    /**
     * 获取大淘客图片的资源
     */
    public void getIndexList(String tags) {

        Map<String, String> params = new HashMap<>();
        String myFav = getFav();
        userFav = getFav();
        params.put("tags", tags);
        if (StringUtils.isNotEmptypro(myFav)&&"推荐".equals(tags)) {
            params.put("fav", myFav);
        }

        String url = NetConfig.INDEX_LIST;
        OkHttpUtils.get()
                .url(url)
                .params(params)

                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        int num = 0;
                        IndexListBean packlist = gson.fromJson(response, IndexListBean.class);
                        code = packlist.getCode();
                        if (code == 200) {
                            List<IndexListBean.DatasBean> itemList = new ArrayList<IndexListBean.DatasBean>();
                            itemList = packlist.getDatas();
                            num = itemList.size();
                            if (num > 0) {
                                mRecyclerView.setVisibility(View.VISIBLE);
                                mEmptyView.setVisibility(View.GONE);
                            } else {
                                mRecyclerView.setVisibility(View.GONE);
                                mEmptyView.setVisibility(View.VISIBLE);
                            }
                            for (int i = 0; i < itemList.size(); i++) {
                                if ("0".equals(itemList.get(i).getType())) {

                                    itemList.get(i).setItemType(1);
                                } else {
                                    if (itemList.get(i).getAds().size() == 1) {
                                        if (itemList.get(i).getAds().get(0).getImgs().size() > 1) {

                                            itemList.get(i).setItemType(2);
                                        } else {

                                            int width = Integer.parseInt(itemList.get(i).getAds().get(0).getWidth());
                                            if (width > 200) {
                                                itemList.get(i).setItemType(4);
                                            } else {

                                                itemList.get(i).setItemType(3);
                                            }

                                        }
                                    } else if (itemList.get(i).getAds().size() > 1) {

                                        itemList.get(i).setItemType(5);
                                    }

                                }
                            }
                            mDataAdapter.addAll(itemList);

                            mRecyclerView.setVisibility(View.VISIBLE);


                        }
                        mRecyclerView.refreshComplete(num);
                    }
                });
    }

    public String getFav() {
        List<String> LikeTags;
        try {
            LikeTags = SharepUtils.getShDataList(getActivity(), SharepUtils.USER_FAV_TAGS_LIST, String.class);
            String tags = "";
            if (LikeTags != null && LikeTags.size() > 0) {
                for (int i = 0; i < LikeTags.size(); i++) {
                    if (i == 0) {
                        tags = LikeTags.get(i);
                    }
                    if (i == 1) {
                        tags = tags + "|" + LikeTags.get(i);
                    }
                    if (i == 2) {
                        tags = tags + "|" + LikeTags.get(i);
                    }
                }
                return tags;

            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取大淘客图片的资源
     */
    public void getIndexListMore(String tags, final int page) {
        Gson gson = new Gson();
        String myFav = getFav();
        Map<Object, Object> map = new HashMap<>();
        map.put("tags", tags);
        map.put("pagecount", page);
        String str = gson.toJson(map);
        String url = NetConfig.INDEX_MORE + "?tags=" + tags;
        if (StringUtils.isNotEmptypro(myFav)&&"推荐".equals(tags)) {

            url = NetConfig.INDEX_MORE + "?tags=" + tags + "&fav=" + myFav;
        } else {
            url = NetConfig.INDEX_MORE + "?tags=" + tags;
        }



        OkHttpUtils.postString()
                .url(url)
                .content(str)
                .addHeader("Content-Type", "application/json")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {


                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        int num = 0;
                        IndexListBean packlist = gson.fromJson(response, IndexListBean.class);
                        code = packlist.getCode();
                        if (code == 200) {
                            List<IndexListBean.DatasBean> itemList = new ArrayList<IndexListBean.DatasBean>();
                            itemList = packlist.getDatas();
                            if (itemList!=null&&itemList.size() > 0) {
                                is_end = false;

                            } else {
                                is_end = true;
                            }
                            num = itemList.size();
                            for (int i = 0; i < itemList.size(); i++) {
                                if ("0".equals(itemList.get(i).getType())) {
                                    itemList.get(i).setItemType(1);
                                } else {
                                    if (itemList.get(i).getAds().size() == 1) {
                                        if (itemList.get(i).getAds().get(0).getImgs().size() > 1) {

                                            itemList.get(i).setItemType(2);
                                        } else {
                                            int width = Integer.parseInt(itemList.get(i).getAds().get(0).getWidth());
                                            if (width > 200) {

                                                itemList.get(i).setItemType(4);
                                            } else {

                                                itemList.get(i).setItemType(3);
                                            }

                                        }
                                    } else if (itemList.get(i).getAds().size() > 1) {

                                        itemList.get(i).setItemType(5);
                                    }

                                }
                            }
                            mDataAdapter.addAll(itemList);

                        }
                        mRecyclerView.refreshComplete(num);
                    }
                });
    }
}
